package mrpanyu.guitool.image;

import java.awt.image.BufferedImage;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.Tool;
import mrpanyu.guitool.base.util.CommonUtils;
import mrpanyu.guitool.base.util.ScreenCapture;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

@ToolModel(displayName = "TesseractOCR", description = "使用tess4j进行OCR解析，Windows上需要本地安装过TesseractOCR的训练数据并配置好TESSDATA_PREFIX环境变量", enableProfiles = false)
public class TesseractOCR {

	@Parameter(displayName = "语言", description = "TesseractOCR语言格式，需要有对应的训练数据，详见Tesseract文档", order = 1)
	private String language = "chi_sim+chi_tra+eng";

	@Action(displayName = "截屏解析", order = 1)
	public void screenCaptureOcr(Tool tool) {
		tool.clearMessages();
		ScreenCapture.capture(img -> {
			ocr(tool, img);
		});
	}

	@Action(displayName = "解析剪贴板图片", order = 2)
	public void clipboardOcr(Tool tool) {
		tool.clearMessages();
		BufferedImage img = CommonUtils.getClipboardImage();
		if (img == null) {
			tool.warnMessage("剪贴板中没有图片信息");
		} else {
			ocr(tool, img);
		}
	}

	private void ocr(Tool tool, BufferedImage img) {
		ITesseract tess = new Tesseract();
		tess.setLanguage(language);
		try {
			String text = tess.doOCR(img);
			tool.infoMessage(text);
		} catch (TesseractException e) {
			tool.errorMessage(e);
		}
	}

}
